﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.IO;
namespace DevTool.Command
{
    /// <summary>
    /// JSON转换扩展类
    /// </summary>
    public static class JsonConver
    {
        /// <summary>
        /// 将字对象转为Json字符串
        /// </summary>
        /// <param name="value">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonString(this object value, String DateTimeFormat = "yyyy/MM/dd HH:mm:ss")
        {
            string result = null;
            if (value != null)
            {
                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = DateTimeFormat;
                result = Newtonsoft.Json.JsonConvert.SerializeObject(value, timeFormat);

            }
            return result;

        }

        /// <summary>
        /// 将字符串转化为对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>对象</returns>
        public static object JsonToObject<T>(this string json)
        {
            object result = null;
            try
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(T));
            }
            catch (Exception e)
            {
                throw e;

            }

            return result;
        }
        /// <summary>
        /// JSON格式化
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertJsonString(this string str)
        {
            //格式化json字符串
            var serializer = new Newtonsoft.Json.JsonSerializer();
            var tr = new StringReader(str);
            var jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                var textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }
    }
}
